from _decimal import Decimal

from rest_framework import serializers
from goods.models import SKU
from .models import OrderInfo, OrderGoods
from django.db import transaction
from datetime import datetime
from django_redis import get_redis_connection


class CartSKUSerializer(serializers.ModelSerializer):
    """购物车商品序列化器"""
    count = serializers.IntegerField(min_value=1)

    class Meta:
        model = SKU
        fields = ('id', 'name', 'default_image_url', 'price', 'count')


class OrderSettlementSerializer(serializers.Serializer):
    """订单结算数据序列化器"""
    freight = serializers.DecimalField(max_digits=10, decimal_places=2)
    skus = CartSKUSerializer(many=True)


class SaveOrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderInfo
        fields = ('order_id', 'pay_method', 'address')
        read_only_fields = ('order_id',)
        extra_kwargs = {
            'address': {
                'write_only': True,
                'required': True
            },
            'pay_method': {
                'write_only': True,
                'required': True
            }
        }

    def create(self, validated_data):
        """保存订单"""
        # 获取当前下单用户
        user = self.context['request'].user
        # 生成订单编号  用当前的时间加上用户订单编号
        order_id = datetime.now().strftime('%Y%m%d%H%M%S') + ('%09d' % user.id)
        address = validated_data['address']
        pay_method = validated_data['pay_method']
        # 生成订单
        with transaction.atomic():
            # 创建一个保存点 如果保存失败则回滚到这个位置
            save_point = transaction.savepoint()
            # conn = get_redis_connection('cart')
            try:
                # 创建订单信息
                order = OrderInfo.objects.create(
                    order_id=order_id,
                    user=user,
                    address=address,
                    total_count=0,
                    total_amount=Decimal(0),
                    freight=Decimal(10),
                    pay_method=pay_method,
                    status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'] if pay_method == OrderInfo.PAY_METHODS_ENUM[
                        'CASH'] else OrderInfo.ORDER_STATUS_ENUM['UNPAID']
                )

                # 从redis中获取购物车结算商品数据
                conn = get_redis_connection('cart')
                cart_hash = conn.hgetall('cart_%s' % user.id)
                selected_set = conn.smembers('cart_select_%s' % user.id)

                # 将bytes类型转换为int类型
                cart = {}
                for sku_id in selected_set:
                    cart[int(sku_id)] = int(cart_hash[sku_id])
                # 一次查询出所有订单商品
                # skus = SKU.objects.filter(id__in=cart.keys())
                sku_id_list = cart.keys()
                for sku_id in sku_id_list:
                    while True:
                        sku = SKU.objects.get(id = sku_id)
                        sku_count = cart[sku.id]

                        # 判断库存
                        origin_stock = sku.stock
                        origin_sales = sku.sales

                        if sku_count > origin_stock:
                            transaction.savepoint_rollback(save_point)
                            raise serializers.ValidationError('商品库存不足')
                        # 减少库存
                        new_stock = origin_stock - sku_count
                        new_sales = origin_sales + sku_count

                        sku.stock = new_stock
                        sku.sales = new_sales
                        sku.save()

                        # 累计商品的spu销量信息
                        sku.goods.sales += sku_count
                        sku.goods.save()

                        # 累计订单基本信息的数据
                        order.total_count += sku_count
                        order.total_amount += (sku.price * sku_count)

                        # 保存订单商品
                        OrderGoods.objects.create(
                            order=order,
                            sku=sku,
                            count=sku_count,
                            price=sku.price
                        )
                        # 更新成功
                        break
                # 更新订单的金额数量信息
                order.total_amount += order.freight
                order.save()
            except Exception as e:
                transaction.savepoint_rollback(save_point)
            else:
                transaction.savepoint_commit(save_point)

                # 更新redis中保存的购物车数据
                pl = conn.pipeline()
                pl.hdel('cart_%s' % user.id, *selected_set)
                pl.srem('cart_select_%s' % user.id, *selected_set)
                pl.execute()
                return order
